package pe.edu.unmsm.fisi.sisconteg.view.controller.login;

import javax.annotation.Resource;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.WebAuthenticationDetails;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
import org.springframework.stereotype.Controller;

import pe.edu.unmsm.fisi.sisconteg.business.service.UsuarioService;
import pe.edu.unmsm.fisi.sisconteg.domain.model.Usuario;


@Controller
@Scope("session")
public class LoginController {

	/*****************ATRIBUTOS**************/
	private Usuario usuario;
	private String paginaActual;
	private String urlMenu;
	
	@Resource(name="MyAuthenticationManager")
	private AuthenticationManager authenticationManager;
	@Resource
	private UsuarioService usuarioService;
	
	/*****************INICIALIZACION**************/
	public LoginController() {
		setUsuario(new Usuario());
	}
	
	/*****************NAVEGACION**************/
	protected HttpServletRequest getRequest() {
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
	    HttpServletRequest request =(HttpServletRequest) context.getRequest();	
	    return request;
	} 
	
	public String loginActionAdmin() throws Exception
	{
		try{
			Authentication aut=validarContextSecurity(usuario.getNickUsuario(), usuario.getPwdUsuario());
	    	if(aut.isAuthenticated()){	    		
	    		setUsuario(usuarioService.obtenerUsuarioxNick(usuario.getNickUsuario()));
	    		setUrlMenu(usuarioService.obtenerMenu(getUsuario().getPerfil()));
	    		HttpSession session=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
				session.setAttribute("usuarioLogueado", usuario);
				if (getUsuario().getPerfil()==1) 
					return "adminPrincipal";
				else
					return "egresadoPrincipal";
	    	}else {
	    		return "error";
			}
		}catch(AuthenticationException e){
			return "error";	}
	}

	public Authentication validarContextSecurity(String usu, String pas)
	{
		HttpServletRequest request= getRequest();
		UsernamePasswordAuthenticationToken authReq=new UsernamePasswordAuthenticationToken(usu, pas);
    	authReq.setDetails(new WebAuthenticationDetails(request));			    	
    	HttpSession session = request.getSession();

    	session.setAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY, usu);
    	Authentication auth = getAuthenticationManager().authenticate(authReq);
        
    	SecurityContext secCtx = SecurityContextHolder.getContext();	    	
    	secCtx.setAuthentication(auth);
    	session.setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, secCtx);   			    	

    	String urlKey = AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY;	   
    	//SavedRequest savedRequest = (SavedRequest)session.getAttribute(urlKey);
    	session.removeAttribute(urlKey);
    	return auth ;
	}
	
	public void cerrarSesion(ActionEvent event)throws Exception{
		String out=cerrarSesionGeneric();
	}

	public String cerrarSesionGeneric() {
		try {
			HttpSession se2=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	    	se2.invalidate();			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "error";
	}
	
	
	/*****************GETTERS AND SETTERS**************/
	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public String getPaginaActual() {
		return paginaActual;
	}

	public void setPaginaActual(String paginaActual) {
		this.paginaActual = paginaActual;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	public String getUrlMenu() {
		return urlMenu;
	}

	public void setUrlMenu(String urlMenu) {
		this.urlMenu = urlMenu;
	}

}
